package com.ys.service.business.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.ys.entity.base.TbSite;
import com.ys.entity.business.*;
import com.ys.mapper.business.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.constant.AppConstant;
import com.ys.dto.AddDto;
import com.ys.entity.business.TpBoutique;
import com.ys.entity.business.TpBoutiqueCart;
import com.ys.entity.business.TpBoutiqueGoods;
import com.ys.entity.business.TpBoutiqueSiteDetail;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.storage.TccStockControl;
import com.ys.entity.sys.YsCol;
import com.ys.enume.business.TpBoutiqueEnum;
import com.ys.service.business.TpBoutiqueService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;


/**
 * 精品库
 */
@Service("tpBoutiqueService")
public class TpBoutiqueServiceImpl implements TpBoutiqueService {
	private static final Logger logger = LoggerFactory.getLogger(TpBoutiqueServiceImpl.class);
	
	@Autowired
	private TpBoutiqueMapper tpBoutiqueMapper;

	@Autowired
	private TpBoutiqueSiteDetailMapper tpBoutiqueSiteDetailMapper;
	@Autowired
	private TpBoutiqueGoodsMapper tpBoutiqueGoodsMapper;
	@Autowired
	private TpBoutiqueCartMapper tpBoutiqueCartMapper;
	@Autowired
	private TpBoutiqueAuthMapper tpBoutiqueAuthMapper;

	@Autowired
	private CheckUtil checkUtil;



	/**
	 * 精品库新增
	 * params参数：code商品编码；name商品名称；codeMerge合并商品编码；boutiqueIsEffect精品是否生效(0未生效，1已生效)
	 */
	@Override
	public R add(TpBoutique tpBoutique) throws Exception{
		tpBoutique.setStatus(1);
		TpProductActive tpProductActive = new TpProductActive().setCode(tpBoutique.getCode()).queryFirst();
		if(tpProductActive!=null){
			if(tpProductActive.getImg()!=null && !"".equals(tpProductActive.getImg())){
				tpBoutique.setCoverImg(tpProductActive.getImg());
			}
		}

		int isAddTpBoutique = tpBoutiqueMapper.insert(tpBoutique);
		if(isAddTpBoutique>0){
			TpBoutiqueSiteDetail tpBoutiqueSiteDetail = new TpBoutiqueSiteDetail();
			tpBoutiqueSiteDetail.setBoutiqueId(tpBoutique.getId());//精品库基础表id（TP_Boutique表Id）
			Map<String,Object> tbSiteList = new TbSite()
					.addLeftJoin("TP_AmazonRegion B ON B.Code = A.RegionCode")
					.addField("B.Name regionName")
					.addLeftJoin("TB_Platform B1 ON B1.Code = B.PlatformCode")
					.addField("B1.Code platformCode")
					.addLeftJoin("TB_Country C ON C.Id = A.CountryId")
					.addField("C.Name countryName")
					.where("C.Name = '英国' AND A.Status!=0 ")
					.queryFirstMap();
			//TpAmazonRegionItem tpAmazonRegionItem = new TpAmazonRegionItem().setCountryName("英国").where("A.Status!=0").queryFirst();
			int isAddTpBoutiqueSite = 0;
			if(tbSiteList!=null && tbSiteList.get("id")!=null) {
				tpBoutiqueSiteDetail.setSiteId(Long.parseLong(tbSiteList.get("id").toString()));//区域站点id
				tpBoutiqueSiteDetail.setStatus(1);
				if(tpBoutique.getCoverImg()!=null && !"".equals(tpBoutique.getCoverImg())){
					tpBoutiqueSiteDetail.setMainPic1(tpBoutique.getCoverImg());
				}
				if(tpProductActive!=null){
					tpBoutiqueSiteDetail.setCommodityLmId(tpProductActive.getCommodityLmId());
					tpBoutiqueSiteDetail.setSizeLength(tpProductActive.getSizeLength());
					tpBoutiqueSiteDetail.setSizeWidth(tpProductActive.getSizeWidth());
					tpBoutiqueSiteDetail.setSizeHeight(tpProductActive.getSizeHeight());
					tpBoutiqueSiteDetail.setSizeWeight(tpProductActive.getSizeWeight());
				}
				isAddTpBoutiqueSite = tpBoutiqueSiteDetailMapper.insert(tpBoutiqueSiteDetail);
			}else {
				return R.error("未查询到默认的英国站点信息");
			}
			if(isAddTpBoutiqueSite<=0){
				return R.error("新增精品表站点信息失败");
			}
		}else {
			return R.error("新增精品表信息失败");
		}
		//return R.ok(AddDto.gotoEdit("/web/business/webTpBoutiqueController/toEdit?id=" ));
		return R.ok();
	}



	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params) {
		logger.info("精品库修改传参："+params);

		TpBoutique tpBoutique = JSON.parseObject(JSON.toJSONString(params), TpBoutique.class);
		//保存权限列表信息
		saveItem(params,tpBoutique);

		tpBoutiqueMapper.update(tpBoutique);
		return R.ok(AddDto.noAction());
	}


	//保存列表信息
	public R saveItem(Map<String, Object> params, TpBoutique tpBoutique){
		//保存列表信息
		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		if(params.get("subData")!=null){
			//验证详情信息
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			String errorBackByItem = null;//错误信息
			if(subData!=null && subData.size()>0){
				for (int i = 0; i < subData.size(); i++) {
					JSONObject jSONObject = subData.getJSONObject(i);
					Map<String, Object> paramsNewByRecord = new HashMap<>();
					if(checkUtil.isNotNullByObject(jSONObject.get("id")))paramsNewByRecord.put("id",jSONObject.get("id"));//id
					if(checkUtil.isNotNullByObject(jSONObject.get("vgsbm")))paramsNewByRecord.put("vgsbm",jSONObject.get("vgsbm"));

					paramsNewByItem.add(paramsNewByRecord);
				}
				if(errorBackByItem!=null && !"".equals(errorBackByItem)){
					return R.error(errorBackByItem);
				}
			}else {
				return R.error("列表信息为空！");
			}
		}else {
			return R.error("列表信息为空！");
		}

		for (int i = 0; i < paramsNewByItem.size(); i++) {
			Map<String, Object> item = paramsNewByItem.get(i);
			TpBoutiqueAuth tpBoutiqueAuth = JSON.parseObject(JSON.toJSONString(item), TpBoutiqueAuth.class);
			tpBoutiqueAuth.setStatus(1);
			tpBoutiqueAuth.setBoutiqueCode(tpBoutique.getCode());
			if(tpBoutiqueAuth.getId()!=null){
				//修改
				tpBoutiqueAuthMapper.update(tpBoutiqueAuth);
			}else {
				//新增
				tpBoutiqueAuthMapper.insert(tpBoutiqueAuth);
			}
		}
		return R.ok();
	}


	//删除
	@Override
	public int del(long id){
		return 0;
	}


	/**
	 * 参数验证
	 */
	@Override
	public String checkParams(Map<String, Object> params,Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TP_Boutique",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		if(!"1".equals(params.get("boutiqueIsEffect").toString()) && !"0".equals(params.get("boutiqueIsEffect").toString())){
			return "未知的逸思精品生效类型！";
		}
		String decimalCount = "2";
		for(YsCol item:listField){
			if(item.getCode().equals("weightPackage")){
				if(params.get(item.getCode())!=null && !checkUtil.isDecimal(params.get(item.getCode()).toString(),decimalCount)){
					backMsg = item.getName()+"应为"+decimalCount+"位小数！";
				}
			}
		}

		return backMsg;
	}

	@Override
	public R list(Integer page, String code, Integer sortType) {
		page = page == null ? 0 : page - 1;
		
		TpBoutique cond = new TpBoutique()
				.where(code != null && code.length() > 0 ? "(A.Code like '%" + code + "%' OR A.Name like '%" + code + "%')" : null);
		List<ListDto.RowDto> rows = new ArrayList<ListDto.RowDto>();
		
		if (sortType == null) {
			cond.setOrderby("A.UpdateTime desc");
		} else if (sortType == 1) {
			cond.setOrderby("(A.NumSaleOld + A.NumSaleNew) asc");
		} else if (sortType == 2) {
			cond.setOrderby("(A.NumSaleOld + A.NumSaleNew) desc");
		} else if (sortType == 3) {
			cond.setOrderby("A.OriginPriceMin asc");
		} else if (sortType == 4) {
			cond.setOrderby("A.OriginPriceMin desc");
		}
		
		cond.addLeftJoin("TP_ProductActive B on B.Code = A.Code")
			.addField("(ISNULL(B.SizeWeight, 0)/1000 - ISNULL(B.SizeLength, 0) * ISNULL(B.SizeWidth, 0) * ISNULL(B.SizeHeight, 0) / 6000) weightVol");
		
		String loginUserId = ShiroUtils.getUserId();
		List<Map<String, Object>> listTpBoutique = cond
				.setBoutiqueIsEffect(TpBoutiqueEnum.BoutiqueIsEffect.YES.value)
				.where("(A.AuthType = " + TpBoutiqueEnum.AuthType.ALL.value + " OR A.Code IN (SELECT AA.BoutiqueCode FROM TP_BoutiqueAuth AA LEFT JOIN THR_OperateCompanyApply BB ON BB.Vgsbm = AA.Vgsbm LEFT JOIN TS_UserChange CC ON CC.Id = BB.OperatorChangeId WHERE CC.UserId = '" + loginUserId + "'))")
				.setPage(page)
				.setSize(15)
				.queryMap();
		for(Map<String, Object> map: listTpBoutique) {
			try {
				TpBoutique entity = (TpBoutique) com.bo.util.MapUtil.mapToObject(map, TpBoutique.class);
				String code2 = entity.getCode();
				String name = entity.getName();
				String img = entity.getCoverImg();
				Integer type = entity.getType();
				String purchasePrice = entity.getOriginPriceRange();
				Integer numStock = new TccStockControl()
						.setProductCode(entity.getCode())
						.setVgsbm(AppConstant.BOUTIQUE_VGSBM)
						.setFields("(ISNULL(SUM(A.ProductNum), 0))").sumDecimal().intValue();
				Integer numBuyer = entity.getNumBuyerOld() + entity.getNumBuyerNew();
				Integer numSale = entity.getNumSaleOld() + entity.getNumSaleNew();
				
				BigDecimal weightVol = new BigDecimal(map.get("weightVol").toString()).setScale(2, BigDecimal.ROUND_HALF_UP);
				
				rows.add(new ListDto.RowDto(code2, name, img, type, purchasePrice, numStock, numBuyer, numSale, weightVol));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		Integer totalNum = cond.count();
		ListDto dto = new ListDto(rows, totalNum);
		return R.ok(dto);
	}
	
	@Override
	public R editSetting(Map<String, Object> param) {

		TpBoutique entity = JSON.parseObject(JSON.toJSONString(param), TpBoutique.class);
		
		tpBoutiqueMapper.update(entity);
		return R.ok();
	}

	@Override
	public R deleteDetail(Long id) {

        if (id == null) {
            return R.error("ID不能为空");
        }
        
        // 验证购物车中是否存在数据
        if (new TpBoutiqueCart().setBoutiqueGoodsId(id).count() > 0) {
			return R.error("购物车中还有此数据，无法修改");
		}

        tpBoutiqueGoodsMapper.deleteTrue(id);
		return R.ok();
	}

	@Override
	public R editDetailBatch(Long boutiqueId, String detailArr) {
		
		if (boutiqueId == null) {
			return R.error("提交的参数有误，请联系客服");
		}
		TpBoutique tpBoutique = new TpBoutique().setId(boutiqueId).queryFirst();
		
		JSONArray detailJA = JSON.parseArray(detailArr);

		// 验证数据是否已存在
		List<String> listUnicode = new ArrayList<String>();
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			String code = detailJO.getString("code");
			String warehouse = detailJO.getString("warehouse");
			
			String unicode = code + tpBoutique.getCode() + warehouse;
			if (listUnicode.contains(unicode)) {
				return R.error("存在重复的商品编码和仓库");
			} else {
				listUnicode.add(unicode);
			}
			
			Integer count = new TpBoutique().setCode(code).count();
			if (count == 0) {
				return R.error("【" + code + "】该商品不存在于精品库");
			}
		}
		
		// 添加调货信息
		BigDecimal originPriceMin = BigDecimal.ZERO;
		BigDecimal originPriceMax = BigDecimal.ZERO;
		for (int i = 0; i < detailJA.size(); i++) {

			JSONObject detailJO = detailJA.getJSONObject(i);
			
			BigDecimal retailPrice = detailJO.getBigDecimal("retailPrice");
			BigDecimal originPrice = detailJO.getBigDecimal("originPrice");

			String code = detailJO.getString("code");
			String attr = detailJO.getString("attr");
			String warehouse = detailJO.getString("warehouse");
			String size = detailJO.getString("size");
			String weight = detailJO.getString("weight");
			String unitName = detailJO.getString("unitName");
			Integer period = detailJO.getInteger("period");
			Integer numPerBox = detailJO.getInteger("numPerBox");
			Integer numBuyMin = detailJO.getInteger("numBuyMin");
			Integer numBuyMinSecond = detailJO.getInteger("numBuyMinSecond");
			Integer numAll = detailJO.getInteger("numAll");
			Integer numPreBuy = detailJO.getInteger("numPreBuy");
			String timeArrivePredict = detailJO.getString("timeArrivePredict");
			
			if (detailJO.containsKey("id")) {
				Long id = detailJO.getLong("id");
				TpBoutiqueGoods entity = new TpBoutiqueGoods().setId(id).queryFirst();
				entity.setCode(code)
					.setAttr(attr)
					.setWarehouse(warehouse)
					.setSize(size)
					.setWeight(weight)
					.setUnitName(unitName)
					.setPeriod(period)
					.setNumPerBox(numPerBox)
					.setNumBuyMin(numBuyMin)
					.setNumBuyMinSecond(numBuyMinSecond)
					.setNumAll(numAll)
					.setNumPreBuy(numPreBuy)
					.setTimeArrivePredict(timeArrivePredict)
					.setRetailPrice(retailPrice)
					.setOriginPrice(originPrice);
				tpBoutiqueGoodsMapper.update(entity);
			} else {

				TpBoutiqueGoods entity = TpBoutiqueGoods.tpBoutiqueGoods(
						code, tpBoutique.getCode(), attr, warehouse,
						size, weight, retailPrice, originPrice,
						numPerBox, numBuyMin, numBuyMinSecond, unitName, period, timeArrivePredict, numAll, numPreBuy, 1);
				tpBoutiqueGoodsMapper.insert(entity);
			}

			// 处理最小和最大金额
			if (i == 0) {
				originPriceMin = originPrice;
				originPriceMax = originPrice;
			}
			originPriceMin = originPriceMin.compareTo(originPrice) <= 0 ? originPriceMin : originPrice;
			originPriceMax = originPriceMax.compareTo(originPrice) >= 0 ? originPriceMax : originPrice;
		}

		String originPriceRange = originPriceMin.toString();
		if (originPriceMin.compareTo(originPriceMax) != 0) {
			originPriceRange = originPriceMin + "~" + originPriceMax;
		}

		tpBoutique.setOriginPriceRange(originPriceRange)
			.setOriginPriceMin(originPriceMin)
			.setOriginPriceMax(originPriceMax);
		tpBoutiqueMapper.update(tpBoutique);
		return R.ok();
	}
	
	@Override
	public R addToCart(String choiceShop) {
		
		LoginUser loginUser = ShiroUtils.getLoginUser();
		String loginUserId = loginUser.getUserId();
		
		JSONArray choiceShopJA = JSON.parseArray(choiceShop);
		for (int i = 0; i < choiceShopJA.size(); i++) {
			JSONObject JO = choiceShopJA.getJSONObject(i);
			String productCode = JO.getString("code");
			TpProductActive productActive = new TpProductActive().setCode(productCode).queryFirst();
			Long boutiqueGoodsId = JO.getLong("id");
			TpBoutiqueGoods productCarefullySetting = new TpBoutiqueGoods().setId(boutiqueGoodsId).queryFirst();

			// 箱数为0，直接跳过
			Integer numBox = JO.getInteger("numBox");
			if (numBox == null || numBox <= 0) {
				continue;
			}
			
			TpBoutiqueCart entity = new TpBoutiqueCart().setBoutiqueGoodsId(boutiqueGoodsId).setCreateUserId(loginUserId).queryFirst();
			if (entity != null) {
				entity.setNumBox(entity.getNumBox() + numBox);
				entity.setNumAllot(entity.getNumBox()* entity.getNumPerBox());
				entity.setTotalPrice(entity.getOriginPrice().multiply(new BigDecimal(entity.getNumAllot())));
				tpBoutiqueCartMapper.update(entity);
			} else {
				entity = new TpBoutiqueCart();
				entity.setBoutiqueGoodsId(boutiqueGoodsId);
				entity.setProductCode(productCode);
				entity.setProductName(productActive.getName());
				entity.setNumBuyMin(productCarefullySetting.getNumBuyMin());
				entity.setNumPerBox(productCarefullySetting.getNumPerBox());
				
				entity.setNumBox(numBox);
				Integer numAllot = numBox * productCarefullySetting.getNumPerBox();
				entity.setNumAllot(numAllot);
				entity.setOriginPrice(productCarefullySetting.getOriginPrice());
				entity.setTotalPrice(productCarefullySetting.getOriginPrice().multiply(new BigDecimal(numAllot)));
				entity.setCreateUserId(loginUserId);
				entity.setCreateUserName(loginUser.getUserName());
				entity.setStatus(1);
				tpBoutiqueCartMapper.insert(entity);
			}
		}
		
		Object data = new TpBoutiqueCart().setCreateUserId(loginUserId).count();
		return R.ok(data);
	}

	@Override
	public R removeFromCart(Long cartId) {
		if (cartId == null) {
			return R.error("购物车ID不能为空");
		}
		
		tpBoutiqueCartMapper.deleteTrue(cartId);
		return R.ok();
	}

	/**
	 * 批量导入精品库信息
	 */
	@Override
	public R importInfo(String rows,Long menuId){
		logger.info("精品库导入的数据：\n"+rows);
		try {
			//获取所有的精品库信息
			List<TpBoutique> tpBoutiqueList = new TpBoutique().queryList();

			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
				//验证导入字段
				String backMsg = "";
				//获取pc字段数据
				List<YsCol> listField = new YsCol()
						.where("A.MenuId = "+menuId)
						.setOrderby("A.SortNo ASC")
						.queryList();
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsg = checkUtil.checkTableColLengthAndDataType(
						"TP_Boutique",
						listField,
						infoMap,
						ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
								&& !"id".equals(ysColItem.getCode())
								&& !"name".equals(ysColItem.getCode()) && !"codeMerge".equals(ysColItem.getCode())
								&& !"type".equals(ysColItem.getCode()) && !"boutiqueIsEffect".equals(ysColItem.getCode())
				);

				if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
					logger.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					return R.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					//continue;
				}
				//验证商品编码
				if(info.get("code")==null || "".equals(info.get("code"))){
					logger.error("第"+(i+1)+"条数据商品编码为空");
					return R.error("第"+(i+1)+"条数据商品编码为空");
					//continue;
				}
				List<TpBoutique> tpBoutique = tpBoutiqueList.stream().filter(item->item.getCode().equals(info.get("code").toString())).collect(Collectors.toList());
				if(tpBoutique.size()<=0){
					logger.error("第"+(i+1)+"条数据商品编码有误");
					return R.error("第"+(i+1)+"条数据商品编码有误");
					//continue;
				}
				infoMap.put("id",tpBoutique.get(0).getId());
				TpBoutique updateDate = JSON.parseObject(JSON.toJSONString(infoMap), TpBoutique.class);
				//编辑
				tpBoutiqueMapper.update(updateDate);
			}

		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}


		return R.ok("导入成功！");
	}


	//精品库权限删除
	@Override
	public R delByAuth(Long id) {
		tpBoutiqueAuthMapper.deleteTrue(id);
		return R.ok();
	}

}
